import { httpClient, withRetry } from './http';
import {
  Config,
  CreateConfigRequest,
  ApiResponse,
} from '../types';

export class ConfigService {
  private static instance: ConfigService;

  private constructor() {}

  public static getInstance(): ConfigService {
    if (!ConfigService.instance) {
      ConfigService.instance = new ConfigService();
    }
    return ConfigService.instance;
  }

  /**
   * 获取所有配置
   */
  public async getAllConfigs(): Promise<ApiResponse<Config[]>> {
    return withRetry(
      async () => httpClient.get<ApiResponse<Config[]>>('/configs'),
      2,
      1000
    )();
  }

  /**
   * 根据名称获取配置
   */
  public async getConfig(name: string): Promise<ApiResponse<Config>> {
    return withRetry(
      async () => httpClient.get<ApiResponse<Config>>(`/configs/${name}`),
      2,
      1000
    )();
  }

  /**
   * 创建配置
   */
  public async createConfig(config: CreateConfigRequest): Promise<ApiResponse<Config>> {
    return httpClient.post<ApiResponse<Config>>('/configs', config);
  }

  /**
   * 更新配置
   */
  public async updateConfig(name: string, config: Partial<CreateConfigRequest>): Promise<ApiResponse<Config>> {
    return httpClient.put<ApiResponse<Config>>(`/configs/${name}`, config);
  }

  /**
   * 删除配置
   */
  public async deleteConfig(name: string): Promise<ApiResponse<void>> {
    return httpClient.delete<ApiResponse<void>>(`/configs/${name}`);
  }

  /**
   * 备份配置
   */
  public async backupConfig(name: string): Promise<ApiResponse<{
    backup_id: string;
    backup_time: string;
  }>> {
    return httpClient.post<ApiResponse<any>>(`/configs/${name}/backup`);
  }

  /**
   * 恢复配置
   */
  public async restoreConfig(name: string, backupId: string): Promise<ApiResponse<Config>> {
    return httpClient.post<ApiResponse<Config>>(`/configs/${name}/restore`, {
      backup_id: backupId,
    });
  }

  /**
   * 获取配置历史
   */
  public async getConfigHistory(name: string): Promise<ApiResponse<Array<{
    version: number;
    value: any;
    created: string;
    created_by: string;
    comment?: string;
  }>>> {
    return httpClient.get<ApiResponse<any>>(`/configs/${name}/history`);
  }

  /**
   * 批量更新配置
   */
  public async batchUpdateConfigs(configs: Array<{
    name: string;
    value: any;
    comment?: string;
  }>): Promise<ApiResponse<{
    success: number;
    failed: number;
    errors: Array<{
      name: string;
      error: string;
    }>;
  }>> {
    return httpClient.post<ApiResponse<any>>('/configs/batch', { configs });
  }

  /**
   * 搜索配置
   */
  public async searchConfigs(query: {
    keyword?: string;
    type?: string;
    page?: number;
    pageSize?: number;
  }): Promise<ApiResponse<{
    items: Config[];
    total: number;
    page: number;
    pageSize: number;
  }>> {
    return httpClient.get<ApiResponse<any>>('/configs/search', { params: query });
  }

  /**
   * 验证配置值
   */
  public async validateConfig(config: {
    name: string;
    value: any;
    type: string;
  }): Promise<ApiResponse<{
    valid: boolean;
    errors: string[];
  }>> {
    return httpClient.post<ApiResponse<any>>('/configs/validate', config);
  }

  /**
   * 导出配置
   */
  public async exportConfigs(configNames?: string[]): Promise<Blob> {
    const params = configNames ? { names: configNames.join(',') } : {};
    const response = await httpClient.get('/configs/export', {
      params,
      responseType: 'blob',
    });
    return response as unknown as Blob;
  }

  /**
   * 导入配置
   */
  public async importConfigs(file: File, options?: {
    overwrite?: boolean;
    validate?: boolean;
  }): Promise<ApiResponse<{
    imported: number;
    skipped: number;
    failed: number;
    errors: Array<{
      name: string;
      error: string;
    }>;
  }>> {
    const formData = new FormData();
    formData.append('file', file);
    if (options) {
      formData.append('options', JSON.stringify(options));
    }
    
    return httpClient.post<ApiResponse<any>>('/configs/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  }

  /**
   * 获取配置统计
   */
  public async getConfigStats(): Promise<ApiResponse<{
    total: number;
    by_type: Record<string, number>;
    recent_changes: Array<{
      name: string;
      changed_at: string;
      changed_by: string;
    }>;
  }>> {
    return withRetry(
      async () => httpClient.get<ApiResponse<any>>('/configs/stats'),
      2,
      1000
    )();
  }

  /**
   * 获取配置依赖关系
   */
  public async getConfigDependencies(name: string): Promise<ApiResponse<{
    dependencies: string[];
    dependents: string[];
  }>> {
    return httpClient.get<ApiResponse<any>>(`/configs/${name}/dependencies`);
  }

  /**
   * 测试配置应用
   */
  public async testConfig(name: string, value: any): Promise<ApiResponse<{
    success: boolean;
    error?: string;
    warnings: string[];
  }>> {
    return httpClient.post<ApiResponse<any>>(`/configs/${name}/test`, { value });
  }

  /**
   * 获取配置模板
   */
  public async getConfigTemplates(): Promise<ApiResponse<Array<{
    name: string;
    description: string;
    type: string;
    default_value: any;
    required: boolean;
    validation_rules?: any;
  }>>> {
    return httpClient.get<ApiResponse<any>>('/configs/templates');
  }

  /**
   * 从模板创建配置
   */
  public async createFromTemplate(template: {
    template_name: string;
    config_name: string;
    value?: any;
    description?: string;
  }): Promise<ApiResponse<Config>> {
    return httpClient.post<ApiResponse<Config>>('/configs/from-template', template);
  }
}

// 导出单例实例
export const configService = ConfigService.getInstance();

export default configService;
